<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Income Expectations Survey</title>
    <!-- 引入 flexible.js CDN -->
    <script src="./js/flexible.js"></script>
    <!-- 引入 Vue.js CDN -->
    <script src="./js/vue@2.js"></script>
    <script src="./js/axios.js"></script>
    <style>
        body, html, #app {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            font-family: Arial, sans-serif;
            background: url('images/bg.png') no-repeat center center;
            background-size: cover;
            color: white;
            overflow: hidden;
        }
        .container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: calc(100% - 10vh);
            padding: 20px;
            box-sizing: border-box;
            overflow-y: auto;
            max-height: 80vh;
            margin-top: 5vh;
        }
        .section {
            width: 100%;
            max-width: 400px;
            margin-bottom: 25px;
        }
        .section-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 25px;
        }
        .radio-group, .input-group {
            display: flex;
            flex-direction: column;
        }
        .group-item {
            min-height: 50px;
            text-align: center;
            position: relative;
        }
        .select-name {
            font-size: 16px;
        }
        .radio-group .radio-item {
            background-color: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            padding: 12px 10px;
            margin-bottom: 10px;
            cursor: pointer;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }
        .icon-select {
            display: inline-block;
            border: 1px solid #fff;
            border-radius: 20px;
            width: 14px;
            height: 14px;
            text-align: center;
            margin-right: 16px;
        }
        .icon-select img {
            width: 12px;
            height: 12px;
            vertical-align: middle;
            margin-top: -1px;
        }
        .radio-group .radio-item.active {
            background-color: rgba(71,120,255, 0.3);
            border-color: #4285f4;
        }
        .radio-group label::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 10px;
            transform: translateY(-50%);
            width: 16px;
            height: 16px;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.5);
        }
        .input-group input {
            background-color: rgba(255, 255, 255, 0);
            border: none;
            border-bottom: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 0px;
            padding: 10px;
            margin-bottom: 10px;
            color: white;
            font-size: 14px;
        }
        .button {
            width: calc(100% - 40px);
            height: 48px;
            line-height: 48px;
            font-size: 16px;
            color: white;
            background-color: #4778FF;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            text-transform: uppercase;
            position: fixed;
            bottom: 8vh;
            left: 20px;
        }
        .show-temp {
            width: 100%;
            max-width: 400px;
            margin-bottom: 25px;
        }
        .max-scroll {

        }
    </style>
</head>
<body>
    <div id="app">
            <div  class="container">
                <div class="section" v-for="(gItem, idx) in question" :key="idx">
                    <div v-show="gItem.show">
                        <div class="section-title">{{ gItem.q }}</div>
                        <div class="radio-group" v-if="gItem.type === 'radio' || gItem.type === 'select'">
                            <div class="radio-item" 
                                v-for="(item, index) in gItem.list" 
                                :class="{ active: item.active }" 
                                :key="index" 
                                @click="handleItem(idx, item, index, gItem)">
                                <i class="icon-select" v-if="gItem.type === 'radio'">
                                    <img v-if="item.active" src="./images/select.png" alt="">
                                </i>
                                <span class="select-name">{{ item.text }}</span>
                            </div>
                        </div>
                        <div class="input-group" v-if="gItem.type === 'input'">
                            <input type="text" placeholder="Enter your answer here" v-model="selectedOptions[gItem.key]">
                        </div>
                    </div>
                </div>
            </div>


            <button class="button next" @click="next" v-if="totalPage > currentPage && totalPage!==0">Next Page</button>

            <button class="button" v-else @click="submitSelection">Submit Selection</button>
    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                selectedOptions: {},
                extraIncome: '',
                question: [],
                question2: [],
                totalPage: 1,
                currentPage: 1,
                originJson: []
            },
            created() {
                this.getList()
            },
            methods: {
                showQuestion() {
                    let curPageQ = this.originJson[this.currentPage - 1];
                    console.log('curPageQ~~', curPageQ);
                    
                    // 初始化一个新的问题数组
                    let newQ = [];

                    // 遍历 this.question 中的每个问题
                    for (let i = 0; i < this.question.length; i++) {
                        const item = this.question[i];
                        let shouldShow = false; // 是否应该显示该问题的标志

                        // 遍历当前页的问题 curPageQ
                        for (let a = 0; a < curPageQ.length; a++) {
                            const qItem = curPageQ[a];

                            // 如果当前问题的 qId 与当前页的问题的 id 匹配
                            if (item.qId === qItem.id) {
                                shouldShow = true; // 设置应该显示该问题
                                break; // 跳出内层循环，因为已经确定要显示该问题
                            }
                        }

                        // 根据 shouldShow 的值来设置问题的显示状态
                        this.$set(this.question[i], 'show', shouldShow);
                    }
                },

                next() {
                    // 当前页有几道题
                    let showCunt = 0
                    for (let i = 0; i < this.question.length; i++) {
                        const element = this.question[i];
                        if(element.show) {
                            showCunt++
                        }
                    }
                    // 已经回答几道题
                    for (let i = 0; i < this.question.length; i++) {
                        const element = this.question[i];
                        if(element.type=== 'select') {
                            // 如果是 select 类型，处理多选
                            let selectedValues = [];
                            for (let a = 0; a < element.list.length; a++) {
                                const item = element.list[a];
                                if (item.active) {
                                    selectedValues.push(item.value);
                                }
                            }
                            // 将选中的值用逗号分隔并设置到 selectedOptions 中
                            this.selectedOptions[element.key] = selectedValues.join(',');
                        }else {
                            for (let a = 0; a < element.list.length; a++) {
                                const item = element.list[a];
                                if(item.active) {
                                    this.selectedOptions[element.key] = item.value
                                }
                            }
                        }
                    }
                    let aCunt = 0
                    for (const iterator in this.selectedOptions) {
                        if(this.selectedOptions[iterator] !== '') {
                            aCunt++
                        }
                    }
                    if(showCunt > aCunt) {
                        return
                    }
                    this.currentPage++
                    this.showQuestion()
                    
                },
                
                getQueryString(name) {
                    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
                    var r = window.location.search.substr(1).match(reg);
                    if (r != null) {
                        return unescape(r[2]);
                    }
                    return null;
                },
                 transformData(data) {
                    const transformedQuestions = [];
                    
                    data.questions.forEach((questionArray, index) => {
                        const transformedQuestionArray = questionArray.map((question, qIndex) => {
                            // Determine the type based on the question index
                            let type;
                            if (question.type === 1) {
                                type = 'radio';
                            } else if (question.type === 2) {
                                type = 'select';
                            } else {
                                type = 'input';
                            }
                            console.log('question~~', question);
                            return {
                                type: type,
                                q: question.content,
                                key: `key${question.id}`,
                                qId: question.id,
                                list: question.options ? question.options.map(item => ({
                                    text: item.content,
                                    value: item.id
                                })) : []
                            };
                        });

                        transformedQuestions.push(transformedQuestionArray);
                    });

                    return {
                        question2: transformedQuestions,
                        survey: {
                            title: data.survey.title,
                            img: data.survey.img,
                            end_title: data.survey.end_title,
                            end_description: data.survey.end_description,
                            end_img: data.survey.end_img,
                        }
                    };
                },
                getList() {
                    // axios({
                    // method: 'get',
                    // url: 'https://app.jips.cc/api/index/getQuestions',
                    // headers: {
                    //     lang: this.getQueryString('lang') || 'en'
                    // },
                    // })
                    // .then((resData)=> {
                    //     console.log('response', resData);
                    //     this.originJson = JSON.parse(JSON.stringify(resData.data.data.questions))
                    //     this.totalPage = this.originJson.length
                    //     console.log('copyJson',this.copyJson);
                    //     const frontendData = this.transformData(resData.data.data || []);
                    //     console.log('resData~~~~~~',frontendData);
                    //     let newFrontendData =  []
                    //     frontendData.question2.forEach(item=> {
                    //         newFrontendData.push(...item)
                    //     })
                    //     console.log('3333333',newFrontendData);
                    //     this.question = newFrontendData
                    //     this.showQuestion()
                    // }).catch(err=> {
                    //     console.log('err', err);
                    // });
                    let resData = {
                        "data": {
                            "code": 1,
                            "show": 0,
                            "msg": "success",
                            "data": {
                                "questions": [
                                    [
                                        {
                                            "id": 1,
                                            "content": "First Name",
                                            "type": 3,
                                            "options": []
                                        },
                                        {
                                            "id": 2,
                                            "content": "Last Name",
                                            "type": 3,
                                            "options": []
                                        }
                                    ],
                                    [
                                        {
                                            "id": 3,
                                            "content": "Contact information",
                                            "type": 1,
                                            "options": [
                                                {
                                                    "id": 1,
                                                    "content": "WhatsApp"
                                                },
                                                {
                                                    "id": 2,
                                                    "content": "Line"
                                                }
                                            ]
                                        },
                                        {
                                            "id": 4,
                                            "content": "What are your hobbies?",
                                            "type": 2,
                                            "options": [
                                                {
                                                    "id": 3,
                                                    "content": "Games"
                                                },
                                                {
                                                    "id": 4,
                                                    "content": "Swimming"
                                                },
                                                {
                                                    "id": 5,
                                                    "content": "Singing"
                                                }
                                            ]
                                        }
                                    ]
                                ],
                                "survey": {
                                    "title": "TAILORED",
                                    "img": "https://app.jips.cc/uploads/images/20240601/202406011519268dfd86878.png",
                                    "end_title": "CONGRATULATIONS",
                                    "end_description": "You Have Completed All Our Questions And Given Us A Positive Review, We Will Immediately Arrange For A Specialist To Contact You Individuallv!",
                                    "end_img": "https://app.jips.cc/uploads/images/20240601/202406011519457cd063987.png"
                                }
                            }
                        },
                        "status": 200,
                        "statusText": "",
                        "headers": {
                            "access-control-allow-credentials": "true",
                            "access-control-allow-headers": "Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,token,version",
                            "access-control-allow-methods": "GET, POST, PATCH, PUT, DELETE, post",
                            "access-control-allow-origin": "*",
                            "access-control-max-age": "1728000",
                            "alt-svc": "h3=\":443\"; ma=86400",
                            "cf-cache-status": "DYNAMIC",
                            "cf-ray": "8963a1be69603de7-SIN",
                            "content-encoding": "br",
                            "content-type": "application/json; charset=utf-8",
                            "date": "Wed, 19 Jun 2024 12:48:10 GMT",
                            "nel": "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}",
                            "report-to": "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v4?s=dl6dw2RTHDZCxBV40lrBkfCvWpDFd8RzyPsiOqDPquRN4VxQNuRjnf5u%2Fv1EBVMRzh6SSp0j8%2BBb8m8%2FdlpQxACad5D9gUlJtavPWhKz528SoBojLNtZ7hlJQxZZ3A%3D%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}",
                            "server": "cloudflare"
                        },
                        "config": {
                            "transitional": {
                                "silentJSONParsing": true,
                                "forcedJSONParsing": true,
                                "clarifyTimeoutError": false
                            },
                            "adapter": [
                                "xhr",
                                "http",
                                "fetch"
                            ],
                            "transformRequest": [
                                null
                            ],
                            "transformResponse": [
                                null
                            ],
                            "timeout": 0,
                            "xsrfCookieName": "XSRF-TOKEN",
                            "xsrfHeaderName": "X-XSRF-TOKEN",
                            "maxContentLength": -1,
                            "maxBodyLength": -1,
                            "env": {},
                            "headers": {
                                "Accept": "application/json, text/plain, */*",
                                "lang": "en"
                            },
                            "method": "get",
                            "url": "https://app.jips.cc/api/index/getQuestions"
                        },
                        "request": {}
                    }
                        this.originJson = JSON.parse(JSON.stringify(resData.data.data.questions))
                        this.totalPage = this.originJson.length
                        console.log('copyJson',this.copyJson);
                        const frontendData = this.transformData(resData.data.data || []);
                        console.log('resData~~~~~~',frontendData);
                        let newFrontendData =  []
                        frontendData.question2.forEach(item=> {
                            newFrontendData.push(...item)
                        })
                        console.log('3333333',newFrontendData);
                        this.question = newFrontendData
                        this.showQuestion()
                },
                handleItem(gIdx, item, idx, gItem) {
                    let group = this.question[gIdx].list
                    console.log('item~~', item);
                    if(gItem.type === 'select') {
                        for (let i = 0; i < group.length; i++) {
                            if(idx === i) {
                                this.$set(this.question[gIdx].list[i], 'active', !item.active)
                            }
                            
                        }
                    }else {
                        for (let i = 0; i < group.length; i++) {
                            if(idx === i) {
                                this.$set(this.question[gIdx].list[i], 'active', true)
                            } else {
                                this.$set(this.question[gIdx].list[i], 'active', false)
                            }
                            
                        }
                    }
 
                },
                transformObject(input) {
                    // 定义目标对象
                    const output = {
                        survey_id: 1,
                        udid: this.getQueryString('uuid'),
                        answer: []
                    };

                    // 遍历输入对象的键值对
                    for (const [key, value] of Object.entries(input)) {
                        // 提取 question_id
                        const question_id = parseInt(key.replace('key', ''), 10);

                        // 添加到 answer 数组中
                        output.answer.push({
                            question_id: question_id,
                            content: value
                        });
                    }

                    return output;
                },
                transformSubmission(frontendData, surveyId, udid) {
                    // 假设我们有一个问题ID和key之间的映射
                    const questionKeyMap = {
                        "key1": 1,
                        "key2": 2,
                        "key3": 3
                    };

                    const answers = Object.keys(frontendData).map(key => ({
                        question_id: questionKeyMap[key],
                        content: frontendData[key]
                    }));

                    return {
                        survey_id: surveyId,
                        udid: udid,
                        answer: answers
                    };
                },
                submitSelection() {
                    for (let i = 0; i < this.question.length; i++) {
                        const element = this.question[i];
                        if(element.type=== 'select') {
                            // 如果是 select 类型，处理多选
                            let selectedValues = [];
                            for (let a = 0; a < element.list.length; a++) {
                                const item = element.list[a];
                                if (item.active) {
                                    selectedValues.push(item.value);
                                }
                            }
                            // 将选中的值用逗号分隔并设置到 selectedOptions 中
                            this.selectedOptions[element.key] = selectedValues.join(',');
                        }else {
                            for (let a = 0; a < element.list.length; a++) {
                                const item = element.list[a];
                                if(item.active) {
                                    this.selectedOptions[element.key] = item.value
                                }
                            }
                        }
                    }
                    console.log('提交内容', JSON.stringify(this.selectedOptions));
                    if(Object.keys(this.selectedOptions).length < this.question.length) {
                        return alert('Please complete the form before submitting!')
                    }
                    let parmas = this.transformObject(this.selectedOptions)
                    console.log('parmas~~',JSON.stringify(parmas));
                    axios({
                    method: 'post',
                    url: 'https://app.jips.cc/api/index/submit',
                    headers: {
                        lang: this.getQueryString('lang') || 'en',
                        udid: this.getQueryString('udid')
                    },
                    data: {
                        ...parmas
                    },
                    })
                    .then((res)=> {
                        if(res.data.code === 1) {
                            window.location.href = './finish.html'
                        }
                    });
                    
                }
            }
        });
    </script>
</body>
</html>
